package com.hydra.wiki.controller;

import com.alibaba.fastjson.JSON;
import com.hydra.wiki.authority.service.UserServiceInter;
import com.hydra.wiki.core.page.ViewMode;
import com.hydra.wiki.doc.domain.Doc;
import com.hydra.wiki.doc.domain.FarmDoctype;
import com.hydra.wiki.doc.domain.ex.DocEntire;
import com.hydra.wiki.doc.domain.ex.TypeBrief;
import com.hydra.wiki.doc.server.*;
import com.hydra.wiki.doc.server.FarmDocOperateRightInter.POP_TYPE;
import com.hydra.wiki.doc.util.ExcelUtils;
import com.hydra.wiki.know.service.KnowServiceInter;
import com.hydra.wiki.parameter.FarmParameterService;
import com.hydra.wiki.web.WebUtils;
import com.hydra.wiki.webfile.server.WcpWebFileManagerInter;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hydra.wiki.util.ThemesUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 资源文件
 */
@RequestMapping("/webfile")
@Controller
@Log4j
public class WebFileController extends WebUtils {
    @Resource
    private FarmDocgroupManagerInter farmDocgroupManagerImpl;
    @Resource
    private FarmFileManagerInter farmFileManagerImpl;
    @Resource
    private FarmDocManagerInter farmDocManagerImpl;
    @Resource
    private FarmDocRunInfoInter farmDocRunInfoImpl;
    @Resource
    private FarmDocmessageManagerInter farmDocmessageManagerImpl;
    @Resource
    private FarmDocOperateRightInter farmDocOperateRightImpl;
    @Resource
    private UserServiceInter userServiceImpl;
    @Resource
    private WcpWebFileManagerInter wcpWebFileManagerImpl;
    @Resource
    private FarmDocTypeInter farmDocTypeManagerImpl;
    @Resource
    private KnowServiceInter KnowServiceImpl;

    @RequestMapping("/add")
    public ModelAndView creatWebFile(String typeid, String groupid, HttpSession session) {
        DocEntire doc = new DocEntire(new Doc());
        if (typeid != null && !typeid.toUpperCase().trim().equals("NONE") && !typeid.toUpperCase().trim().equals("")) {
            FarmDoctype doctype = farmDocTypeManagerImpl.getType(typeid);
            doc.setType(doctype);
        }
        if (groupid != null && !groupid.toUpperCase().trim().equals("NONE")
                && !groupid.toUpperCase().trim().equals("")) {
            doc.getDoc().setDocgroupid(groupid);
        }
        List<TypeBrief> types = farmDocTypeManagerImpl.getTypesForWriteDoc(getCurrentUser(session));

        String filetypeString = FarmParameterService.getInstance().getParameter("config.doc.upload.types").toLowerCase()
                .replaceAll("，", ",");
        StringBuffer filetypestrplus = new StringBuffer();
        for (String node : parseIds(filetypeString)) {
            if (filetypestrplus.length() > 0) {
                filetypestrplus.append(";");
            }
            filetypestrplus.append("*." + node);
        }
        return ViewMode.getInstance().putAttr("types", types).putAttr("doc", doc).putAttr("filetypestr", filetypeString)
                .putAttr("filetypestrplus", filetypestrplus.toString())
                .returnModelAndView(ThemesUtil.getThemePath() + "/webfile/creat");
    }

    @RequestMapping("/batch")
    public ModelAndView batchCreateDoc(HttpSession session) {
        return ViewMode.getInstance()
                .returnModelAndView(ThemesUtil.getThemePath() + "/webfile/batch");
    }

    @PostMapping("/batchUpload.do")
    @ResponseBody
    public Map<String, Object> batchUploadDoc(String writetype, String readtype, HttpSession session,@RequestParam("file") MultipartFile multipartFile) throws IOException {
        int error = 0;
        String message = "";
        String fileName = multipartFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        InputStream inputStream = multipartFile.getInputStream();
        Workbook workbook = null;
        if (extension.equalsIgnoreCase("xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (extension.equalsIgnoreCase("xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        }
        List<TypeBrief> types = farmDocTypeManagerImpl.getTypesForWriteDoc(getCurrentUser(session));
        List<ExcelUtils.DOC> docList;
        List<DocEntire> resultList = new ArrayList<>();
        if (workbook != null){
            docList = ExcelUtils.getDocList(workbook, 0);
            try {
                ExcelUtils.wrapType(docList, types);
            } catch (Exception e) {
                error = 1;
                message = e.getMessage();
            }
            if (CollectionUtils.isNotEmpty(docList)){
                try {
                    for (ExcelUtils.DOC doc : docList) {
                        DocEntire docEntire = KnowServiceImpl.creatKnow(doc.getKnowtitle(), doc.getKnowtypeId(), null, doc.getText(), doc.getKnowtag(), POP_TYPE.PUB,
                                POP_TYPE.PUB, null, getCurrentUser(session));
                        resultList.add(docEntire);
                    }
                } catch (Exception e) {
                    System.out.println(JSON.toJSONString(e));
                }
            }
        } else {
            error = 1;
            message = "请上传EXCEL文件";
        }
        return ViewMode.getInstance()
                .putAttr("error", error)
                .putAttr("message", message)
                .putAttr("result", resultList)
                .returnObjMode();
    }

    @RequestMapping("/edit")
    public ModelAndView editWebfile(String docId, HttpSession session, HttpServletRequest request) {
        DocEntire doc = null;
        try {
            doc = farmDocManagerImpl.getDoc(docId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.toString())
                    .returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
        List<TypeBrief> types = farmDocTypeManagerImpl.getTypesForWriteDoc(getCurrentUser(session));

        String filetypeString = FarmParameterService.getInstance().getParameter("config.doc.upload.types").toLowerCase()
                .replaceAll("，", ",");
        StringBuffer filetypestrplus = new StringBuffer();
        for (String node : parseIds(filetypeString)) {
            if (filetypestrplus.length() > 0) {
                filetypestrplus.append(";");
            }
            filetypestrplus.append("*." + node);
        }
        return ViewMode.getInstance().putAttr("doce", doc).putAttr("types", types)
                .putAttr("filetypestr", filetypeString).putAttr("filetypestrplus", filetypestrplus.toString())
                .returnModelAndView(ThemesUtil.getThemePath() + "/webfile/edit");
    }

    @RequestMapping("/editCommit")
    public ModelAndView editCommit(String docid, String fileId, String knowtype, String knowtitle, String knowtag,
                                   String docgroup, String writetype, String readtype, String text, String editnote, HttpSession session) {
        DocEntire doc = null;
        try {
            if (docgroup.equals("0")) {
                docgroup = null;
            }
            doc = wcpWebFileManagerImpl.editWebFile(docid, Arrays.asList(fileId.trim().split(",")), knowtype, knowtitle,
                    knowtag, docgroup, text, POP_TYPE.getEnum(writetype), POP_TYPE.getEnum(readtype), editnote,
                    getCurrentUser(session));
            if (doc.getAudit() != null) {
                return ViewMode.getInstance().returnRedirectUrl("/audit/tempdoc.do?auditid=" + doc.getAudit().getId());
            }
            return ViewMode.getInstance().returnRedirectUrl("/webdoc/view/Pub" + doc.getDoc().getId() + ".html");
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e.toString())
                    .returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    @RequestMapping("/addsubmit")
    public ModelAndView creatWebFileSubmit(String fileId, String creattype, String knowtype, String knowtitle,
                                           String knowtag, String text, String docgroup, String writetype, String readtype, HttpSession session) {
        try {
            List<String> fileids = Arrays.asList(fileId.trim().split(","));
            if (creattype != null && creattype.equals("on")) {
                /** 创建为独立知识 **/
                Map<String, String> doclinks = new HashMap<String, String>();
                DocEntire doc = null;
                for (String fileid : fileids) {
                    List<String> fileidlist = new ArrayList<>();
                    fileidlist.add(fileid);
                    if (docgroup != null && docgroup.equals("0")) {
                        docgroup = null;
                    }
                    String fileName = farmFileManagerImpl.getFile(fileid).getName();
                    doc = wcpWebFileManagerImpl.creatWebFile(fileidlist, knowtype, fileName, knowtag, docgroup, text,
                            POP_TYPE.getEnum(writetype), POP_TYPE.getEnum(readtype), getCurrentUser(session));
                    if (doc.getAudit() != null) {
                        doclinks.put(fileName, "/audit/tempdoc.do?auditid=" + doc.getAudit().getId());
                    } else {
                        doclinks.put(fileName, "/webdoc/view/Pub" + doc.getDoc().getId() + ".html");
                    }
                }
                if (doc.getAudit() != null) {
                    return ViewMode.getInstance().putAttr("MESSAGE", fileids.size() + "个资源文件创建成功，但是需要审核后才能够被他人访问！")
                            .returnModelAndView(ThemesUtil.getThemePath() + "/message");
                }
                return ViewMode.getInstance().putAttr("MESSAGE", fileids.size() + "个资源文件创建成功！")
                        .putAttr("LINKS", doclinks).returnModelAndView(ThemesUtil.getThemePath() + "/message");
            } else {
                /** 创建为一个知识 **/
                DocEntire doc = null;
                if (docgroup.equals("0")) {
                    docgroup = null;
                }
                doc = wcpWebFileManagerImpl.creatWebFile(fileids, knowtype, knowtitle, knowtag, docgroup, text,
                        POP_TYPE.getEnum(writetype), POP_TYPE.getEnum(readtype), getCurrentUser(session));
                if (doc.getAudit() != null) {
                    return ViewMode.getInstance()
                            .returnRedirectUrl("/audit/tempdoc.do?auditid=" + doc.getAudit().getId());
                }
                return ViewMode.getInstance().returnRedirectUrl("/webdoc/view/Pub" + doc.getDoc().getId() + ".html");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e.toString())
                    .returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }
}
